package BlogMybatis.blog.service.impl;

import BlogMybatis.blog.exception.NotFoundException;
import BlogMybatis.blog.pojo.Blog;
import BlogMybatis.blog.mapper.BlogMapper;
import BlogMybatis.blog.pojo.BlogAndTags;
import BlogMybatis.blog.pojo.Tag;
import BlogMybatis.blog.service.BlogService;
import BlogMybatis.blog.service.CommentService;
import BlogMybatis.blog.util.MarkdownUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Brandt
 * @since 2020-06-07
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService{

    @Autowired
    private BlogMapper blogMapper;

    @Override
    public List<Blog> getAllBlog() {
        return blogMapper.getAllBlog();
    }

    @Override
    public List<Blog> searchAllBlog(Blog blog) {
        return blogMapper.searchAllBlog(blog);
    }

    @Override
    public Blog getByBlog(Long id) {
        return blogMapper.getByBlog(id);
    }

    @Override
    public int updateBlog(Blog blog) {
        blog.setUpdateTime(new Date());
        List<Tag> tags = blog.getTags();
        BlogAndTags blogAndTags = null;
        for (Tag tag : tags) {
            blogAndTags = new BlogAndTags(tag.getId(),blog.getId());
            blogMapper.saveBlogAndTag(blogAndTags);
        }
        return blogMapper.updateBlog(blog);
    }

    @Override
    public List<Blog> getIndexBlog() {
        return blogMapper.getIndexBlog();
    }

    @Override
    public List<Blog> getAllRecommendBlog() {
        return blogMapper.getAllRecommendBlog();
    }

    @Override
    public Blog getDetailedBlog(Long id) {
        Blog blog = blogMapper.getDetailedBlog(id);
        if(blog == null){
            throw new NotFoundException("该博客不存在");
        }
        String content = blog.getContent();
        blog.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        return blog;
    }

    @Override
    public int updateViews(Long id) {
        return blogMapper.updateViews(id);
    }

    @Override
    public List<Blog> getSearchBlog(String query) {
        return blogMapper.getSearchBlog(query);
    }

    @Override
    public List<Blog> listBlogFooter() {
        return blogMapper.listBlogFooter();
    }

    @Override
    public List<Blog> getByTypeId(Long typeId) {
        return blogMapper.getByTypeId(typeId);
    }

    @Override
    public List<Blog> getByTagId(Long tagId) {
        return blogMapper.getByTagId(tagId);
    }

    @Override
    public List<Blog> archiveShow() {
        return blogMapper.archiveShow();
    }
}
